<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>事件记录系统</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        input, textarea, select {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        button {
            background-color: #4CAF50;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin-right: 5px;
        }
        button:hover {
            opacity: 0.9;
        }
        .btn-edit {
            background-color: #007bff;
        }
        .btn-delete {
            background-color: #dc3545;
        }
        .btn-cancel {
            background-color: #6c757d;
        }
        .message {
            padding: 10px;
            margin: 10px 0;
            border-radius: 4px;
        }
        .success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        th, td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }
        th {
            background-color: #f2f2f2;
        }
        .actions {
            white-space: nowrap;
        }
        .pagination-container {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 20px;
            flex-wrap: wrap;
        }
        .pagination {
            display: flex;
        }
        .pagination button {
            margin: 0 5px;
        }
        .pagination .active {
            background-color: #007bff;
        }
        .edit-row input, .edit-row textarea {
            width: 100%;
            border: 1px solid #ccc;
            padding: 5px;
        }
        .hidden {
            display: none;
        }
        .search-container {
            margin-bottom: 20px;
            display: flex;
            gap: 10px;
            align-items: end;
        }
        .search-container > div {
            flex: 1;
        }
        .page-size-selector {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .search-container button {
            height: 38px;
        }
    </style>
</head>
<body>
    <h1>事件记录系统</h1>

    <form id="eventForm">
        <div class="form-group">
            <label for="datetime">时间:</label>
            <input type="datetime-local" id="datetime" step="1" required>
        </div>

        <div class="form-group">
            <label for="person">主责人员:</label>
            <input type="text" id="person" required>
        </div>

        <div class="form-group">
            <label for="description">事件描述:</label>
            <textarea id="description" rows="4" required></textarea>
        </div>

        <button type="submit">记录事件</button>
    </form>

    <div id="message"></div>

    <div class="search-container">
        <div>
            <label for="searchKeyword">搜索关键字:</label>
            <input type="text" id="searchKeyword" placeholder="搜索时间、人员或描述">
        </div>
        <button onclick="searchEvents()">搜索</button>
        <button onclick="clearSearch()">清空</button>
    </div>

    <div class="pagination-container">
        <div class="page-size-selector">
            <label for="pageSize">每页显示:</label>
            <select id="pageSize" onchange="changePageSize()">
                <option value="10">10条</option>
                <option value="50">50条</option>
                <option value="100">100条</option>
                <option value="500">500条</option>
            </select>
        </div>
        <div class="pagination" id="pagination">
            <!-- 分页按钮将在这里显示 -->
        </div>
    </div>

    <h2>记录列表</h2>
    <table id="eventTable">
        <thead>
            <tr>
                <th>记录时间</th>
                <th>事件时间</th>
                <th>主责人员</th>
                <th>事件描述</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody id="eventList">
            <!-- 记录将在这里显示 -->
        </tbody>
    </table>

    <div class="pagination-container">
        <div></div>
        <div class="pagination" id="pagination-bottom">
            <!-- 分页按钮将在这里显示 -->
        </div>
    </div>

    <script>
        // 全局变量
        let allEvents = [];
        let currentPage = 1;
        let itemsPerPage = 10;
        let editingId = null;
        let searchKeyword = '';

        // 页面加载时获取数据
        document.addEventListener('DOMContentLoaded', function() {
            loadEvents();

            // 设置默认时间为当前时间（包含秒）
            const now = new Date();
            const year = now.getFullYear();
            const month = String(now.getMonth() + 1).padStart(2, '0');
            const day = String(now.getDate()).padStart(2, '0');
            const hours = String(now.getHours()).padStart(2, '0');
            const minutes = String(now.getMinutes()).padStart(2, '0');
            const seconds = String(now.getSeconds()).padStart(2, '0');

            document.getElementById('datetime').value = `${year}-${month}-${day}T${hours}:${minutes}:${seconds}`;

            // 设置默认分页大小
            document.getElementById('pageSize').value = itemsPerPage;
        });

        // 表单提交处理
        document.getElementById('eventForm').addEventListener('submit', function(e) {
            e.preventDefault();

            const datetime = document.getElementById('datetime').value;
            const person = document.getElementById('person').value;
            const description = document.getElementById('description').value;

            // 创建事件对象
            const event = {
                datetime: datetime,
                person: person,
                description: description
            };

            // 发送到后端保存
            fetch('/save_event', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(event)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showMessage('事件记录成功保存到文件中！', 'success');
                    loadEvents(); // 重新加载数据
                    document.getElementById('eventForm').reset();

                    // 重新设置默认时间为当前时间
                    const now = new Date();
                    const year = now.getFullYear();
                    const month = String(now.getMonth() + 1).padStart(2, '0');
                    const day = String(now.getDate()).padStart(2, '0');
                    const hours = String(now.getHours()).padStart(2, '0');
                    const minutes = String(now.getMinutes()).padStart(2, '0');
                    const seconds = String(now.getSeconds()).padStart(2, '0');

                    document.getElementById('datetime').value = `${year}-${month}-${day}T${hours}:${minutes}:${seconds}`;
                } else {
                    showMessage('保存失败: ' + data.message, 'error');
                }
            })
            .catch(error => {
                showMessage('保存失败: ' + error.message, 'error');
            });
        });

        // 显示消息
        function showMessage(text, type) {
            const messageDiv = document.getElementById('message');
            messageDiv.textContent = text;
            messageDiv.className = 'message ' + (type === 'success' ? 'success' : 'error');

            // 3秒后自动清除消息
            setTimeout(() => {
                messageDiv.textContent = '';
                messageDiv.className = '';
            }, 3000);
        }

        // 从后端加载事件
        function loadEvents() {
            fetch('/get_events')
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    allEvents = data.events;
                    // 按记录时间排序（最新的在前）
                    allEvents.sort((a, b) => new Date(b.recorded_at) - new Date(a.recorded_at));
                    filterAndRender();
                } else {
                    showMessage('加载数据失败: ' + data.message, 'error');
                }
            })
            .catch(error => {
                showMessage('加载数据失败: ' + error.message, 'error');
            });
        }

        // 搜索事件
        function searchEvents() {
            searchKeyword = document.getElementById('searchKeyword').value.trim().toLowerCase();
            currentPage = 1; // 重置到第一页
            filterAndRender();
        }

        // 清空搜索
        function clearSearch() {
            document.getElementById('searchKeyword').value = '';
            searchKeyword = '';
            currentPage = 1; // 重置到第一页
            filterAndRender();
        }

        // 过滤并渲染数据
        function filterAndRender() {
            let filteredEvents = allEvents;

            // 应用搜索过滤
            if (searchKeyword) {
                filteredEvents = allEvents.filter(event =>
                    event.datetime.toLowerCase().includes(searchKeyword) ||
                    event.person.toLowerCase().includes(searchKeyword) ||
                    event.description.toLowerCase().includes(searchKeyword)
                );
            }

            renderPage(currentPage, filteredEvents);
            renderPagination(filteredEvents);
        }

        // 渲染当前页
        function renderPage(page, events) {
            const startIndex = (page - 1) * itemsPerPage;
            const endIndex = startIndex + itemsPerPage;
            const pageEvents = events.slice(startIndex, endIndex);

            const tableBody = document.getElementById('eventList');
            tableBody.innerHTML = '';

            if (pageEvents.length === 0) {
                const row = document.createElement('tr');
                row.innerHTML = `<td colspan="5" style="text-align: center;">暂无数据</td>`;
                tableBody.appendChild(row);
                return;
            }

            pageEvents.forEach(event => {
                addEventToTable(event);
            });
        }

        // 渲染分页控件
        function renderPagination(events) {
            const totalPages = Math.ceil(events.length / itemsPerPage);
            const paginationDiv = document.getElementById('pagination');
            const paginationBottomDiv = document.getElementById('pagination-bottom');

            if (totalPages <= 1) {
                paginationDiv.innerHTML = '';
                paginationBottomDiv.innerHTML = '';
                return;
            }

            let paginationHTML = '';

            // 上一页按钮
            if (currentPage > 1) {
                paginationHTML += `<button onclick="changePage(${currentPage - 1})">上一页</button>`;
            }

            // 页码按钮 (最多显示10个页码)
            const startPage = Math.max(1, currentPage - 4);
            const endPage = Math.min(totalPages, currentPage + 5);

            if (startPage > 1) {
                paginationHTML += `<button onclick="changePage(1)">1</button>`;
                if (startPage > 2) {
                    paginationHTML += `<span>...</span>`;
                }
            }

            for (let i = startPage; i <= endPage; i++) {
                if (i === currentPage) {
                    paginationHTML += `<button class="active">${i}</button>`;
                } else {
                    paginationHTML += `<button onclick="changePage(${i})">${i}</button>`;
                }
            }

            if (endPage < totalPages) {
                if (endPage < totalPages - 1) {
                    paginationHTML += `<span>...</span>`;
                }
                paginationHTML += `<button onclick="changePage(${totalPages})">${totalPages}</button>`;
            }

            // 下一页按钮
            if (currentPage < totalPages) {
                paginationHTML += `<button onclick="changePage(${currentPage + 1})">下一页</button>`;
            }

            paginationDiv.innerHTML = paginationHTML;
            paginationBottomDiv.innerHTML = paginationHTML;
        }

        // 切换页面
        function changePage(page) {
            currentPage = page;
            filterAndRender();
        }

        // 更改每页显示条数
        function changePageSize() {
            itemsPerPage = parseInt(document.getElementById('pageSize').value);
            currentPage = 1; // 重置到第一页
            filterAndRender();
        }

        // 添加事件到表格
        function addEventToTable(event) {
            const tableBody = document.getElementById('eventList');
            const row = document.createElement('tr');
            row.id = 'row-' + (event.id || Date.now());

            // 格式化显示记录时间（包含秒）
            const recordedTime = new Date(event.recorded_at).toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit'
            });

            // 格式化显示事件时间（包含秒）
            const eventTime = new Date(event.datetime).toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit'
            });

            row.innerHTML = `
                <td>${recordedTime}</td>
                <td>${eventTime}</td>
                <td>${event.person}</td>
                <td>${event.description}</td>
                <td class="actions">
                    <button class="btn-edit" onclick="editEvent('${event.id || Date.now()}')">编辑</button>
                    <button class="btn-delete" onclick="deleteEvent('${event.id || Date.now()}')">删除</button>
                </td>
            `;

            tableBody.appendChild(row);
        }

        // 编辑事件
        function editEvent(id) {
            // 如果正在编辑其他行，先取消编辑
            if (editingId !== null && editingId !== id) {
                cancelEdit();
            }

            const event = allEvents.find(e => (e.id || Date.now()) == id);
            if (!event) return;

            const row = document.getElementById('row-' + id);
            if (!row) return;

            editingId = id;

            // 格式化时间用于编辑（包含秒）
            const datetimeValue = event.datetime;

            row.innerHTML = `
                <td>${new Date(event.recorded_at).toLocaleString('zh-CN', {
                    year: 'numeric',
                    month: '2-digit',
                    day: '2-digit',
                    hour: '2-digit',
                    minute: '2-digit',
                    second: '2-digit'
                })}</td>
                <td><input type="datetime-local" id="edit-datetime-${id}" value="${datetimeValue}" step="1"></td>
                <td><input type="text" id="edit-person-${id}" value="${event.person}"></td>
                <td><textarea id="edit-description-${id}" rows="3">${event.description}</textarea></td>
                <td class="actions">
                    <button onclick="saveEdit('${id}')">保存</button>
                    <button class="btn-cancel" onclick="cancelEdit()">取消</button>
                </td>
            `;
            row.className = 'edit-row';
        }

        // 保存编辑
        function saveEdit(id) {
            const event = allEvents.find(e => (e.id || Date.now()) == id);
            if (!event) return;

            const updatedEvent = {
                id: event.id,
                datetime: document.getElementById(`edit-datetime-${id}`).value,
                person: document.getElementById(`edit-person-${id}`).value,
                description: document.getElementById(`edit-description-${id}`).value
            };

            // 发送到后端更新
            fetch('/update_event', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(updatedEvent)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showMessage('事件更新成功！', 'success');
                    // 更新本地数据
                    Object.assign(event, updatedEvent);
                    // 重新加载当前页
                    filterAndRender();
                    editingId = null;
                } else {
                    showMessage('更新失败: ' + data.message, 'error');
                }
            })
            .catch(error => {
                showMessage('更新失败: ' + error.message, 'error');
            });
        }

        // 取消编辑
        function cancelEdit() {
            if (editingId !== null) {
                filterAndRender();
                editingId = null;
            }
        }

        // 删除事件
        function deleteEvent(id) {
            if (!confirm('确定要删除这条记录吗？')) {
                return;
            }

            // 发送到后端删除
            fetch('/delete_event', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({id: id})
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showMessage('事件删除成功！', 'success');
                    // 从本地数据中移除
                    allEvents = allEvents.filter(e => (e.id || Date.now()) != id);
                    // 重新加载当前页
                    filterAndRender();
                } else {
                    showMessage('删除失败: ' + data.message, 'error');
                }
            })
            .catch(error => {
                showMessage('删除失败: ' + error.message, 'error');
            });
        }
    </script>
</body>
</html>
